package com.bilibili.juc.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author zuife
 * @description
 * @since 2024-04-20 16:48:35
 */
public class CompletableFutureAPIDemo {
//    /**
//     * 演示超时
//     * @param args
//     * @throws ExecutionException
//     * @throws InterruptedException
//     * @throws TimeoutException
//     */
//    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
//        // 1.supplyAsync 异步执行，返回CompletableFuture
//        // 2.thenApply 方法串行化，第一个方法返回值作为第二个方法的入参
//        // 3.get() 获取最终结果
//        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
//            try {
//                TimeUnit.SECONDS.sleep(3);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            return "ABC";
//        });
//        completableFuture.get(2L,TimeUnit.SECONDS);
//    }

    /**
     * join
     * @param args
     * @throws ExecutionException
     * @throws InterruptedException
     * @throws TimeoutException
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        // 1.supplyAsync 异步执行，返回CompletableFuture
        // 2.thenApply 方法串行化，第一个方法返回值作为第二个方法的入参
        // 3.get() 获取最终结果
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "ABC";
        });
        //暂停两秒
        TimeUnit.SECONDS.sleep(2);
        //System.out.println(completableFuture.join());
        System.out.println(completableFuture.getNow("DEF"));
        System.out.println(completableFuture.complete("completeValue")+"\t"+completableFuture.join());
    }
}
